<!-- subpkg_medicine/payment/index.vue -->
<script lang="ts" setup>
import { getPatientOrderAddressAPI } from '@/api/address'
import { getMedicineOrderPreAPI, createMedicineOrderAPI } from '@/api/order'
import { postPatientConsultPayAPI } from '@/api/consult'
import CustomPayment from '@/components/custom-payment/custom-payment.vue'
import type { AddressItem } from '@/types/address'
import type { MedicineOrderPre } from '@/types/order'
import { ref } from 'vue'

// 获取收货地址列表
const addressList = ref<AddressItem>()
const getAddressList = async () => {
  const res = await getPatientOrderAddressAPI()
  console.log('收货地址列表', res)

  addressList.value = res.find((item) => item.isDefault === 1)
}
getAddressList()

// 接收处方ID
const props = defineProps<{
  id: string
}>()
// 订单预支付信息
const orderPre = ref<MedicineOrderPre>()
// 获取预支付信息
const getOrderPre = async () => {
  if (!props.id) return
  const res = await getMedicineOrderPreAPI({ prescriptionId: props.id })
  orderPre.value = res
  console.log(res)
}
getOrderPre()

// 跳转到地址列表
const onAddressClick = () => {
  uni.navigateTo({ url: '/subpkg_medicine/address/address' })
}

// 订单ID
const orderId = ref('')

// 确认支付
const customPaymentRef = ref<InstanceType<typeof CustomPayment>>()
const onConfirm = async () => {
  if (!addressList.value?.id) {
    uni.showToast({
      title: '请选择收货地址',
      icon: 'none',
    })
    return
  }

  // 不能重复创建订单
  if (orderId.value) {
    uni.showToast({
      title: '不能重复创建订单',
      icon: 'none',
    })
    return
  }

  try {
    // 1. 创建订单
    const res = await createMedicineOrderAPI({
      id: props.id,
      addressId: addressList.value.id,
    })
    orderId.value = res.id
    console.log('创建的订单id', res)
    // 2. 打开支付弹窗
    customPaymentRef.value?.open()
  } catch (error) {
    uni.showToast({
      title: '创建订单失败',
      icon: 'error',
    })
    console.log(error)
  }
}

// 支付方式改变
const onPaymentChange = (index: number) => {
  console.log('支付方式改变', index)
}

// 确认支付
const onPaymentConfirm = async (index: number) => {
  if (index === 0) {
    uni.showToast({
      title: '暂不支持微信支付',
      icon: 'none',
    })
    // #ifdef MP-WEIXIN
    // 微信支付相关逻辑
    // #endif
  } else if (index === 1) {
    // 根据当前网址,获取基地址
    const baseUrl = window.location.origin
    const payCallback = `${baseUrl}/#/subpkg_medicine/pay_result/pay_result`
    // 支付宝支付
    const res = await postPatientConsultPayAPI({
      orderId: orderId.value,
      paymentMethod: '1',
      payCallback,
    })
    console.log('支付结果', res)
    location.href = res.payUrl
  }
}

// 关闭支付组件
const onClose = async () => {
  const res = await uni.showModal({
    title: '关闭支付',
    content: '取消支付将无法获得药品，是否确认关闭？',
    cancelText: '仍要关闭',
    cancelColor: '#848484',
    confirmText: '继续支付',
    confirmColor: '#16C2A3',
  })
  if (res.cancel) {
    customPaymentRef.value?.close()
  }
}
</script>

<template>
  <scroll-view background-color="#f6f6f6">
    <view class="medicine-page">
      <view class="page-header">
        <view class="order-shippment" @tap="onAddressClick">
          <view class="region">
            <uni-icons size="16" color="#FF7702" type="location-filled" />
            {{ addressList?.province }} {{ addressList?.city }}
          </view>
          <view class="detail">
            {{ addressList?.addressDetail }}
          </view>
          <view class="receiver">
            {{ addressList?.receiver }}
            {{ addressList?.mobile?.replace(/(\d{3})(\d{4})(\d{4})/, '$1****$2') }}
          </view>
        </view>
      </view>

      <view class="order-shop">
        优医药房
        <text class="alt">优医质保 假一赔十</text>
      </view>
      <!-- 药品列表 -->
      <view class="medicine-list">
        <view class="medicine-list-item" v-for="item in orderPre?.medicines" :key="item.id">
          <image class="medicine-cover" :src="item.avatar" mode="aspectFill" />
          <view class="medicine-info">
            <text class="name">{{ item.name }}</text>
            <text class="unit symbol">{{ item.specs }}</text>
            <text class="price">¥{{ item.amount }}</text>
          </view>
          <view class="quantity">x{{ item.quantity }}</view>
          <view class="guide">用法用量：{{ item.usageDosag }}</view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="order-info">
        <uni-list :border="false">
          <uni-list-item title="药品金额" :right-text="`¥${orderPre?.payment || '0.00'}`" />
          <uni-list-item title="运费" :right-text="`¥${orderPre?.expressFee || '0.00'}`" />
          <uni-list-item
            title="优惠券"
            show-arrow
            :right-text="`-¥${orderPre?.couponDeduction || '0.00'}`"
          />
          <uni-list-item title="实付款" :right-text="`¥${orderPre?.actualPayment || '0.00'}`" />
        </uni-list>
      </view>

      <!-- 底部 -->
      <view class="toolbar">
        <view class="total-amount">
          需付款: <text class="number">¥{{ orderPre?.actualPayment || '0.00' }}</text>
        </view>
        <view class="buttons">
          <button class="uni-button" @tap="onConfirm">立即支付</button>
        </view>
      </view>
    </view>
  </scroll-view>

  <!-- 支付组件 -->
  <CustomPayment
    ref="customPaymentRef"
    v-if="orderPre"
    :amount="orderPre?.actualPayment"
    :order-id="orderId"
    @close="onClose"
    @change="onPaymentChange"
    @confirm="onPaymentConfirm"
  />
</template>

<style lang="scss">
@import './index.scss';
</style>
